package com.telecomyt.jwportal.http;


import android.util.Log;

import com.telecomyt.jwportal.BaseApplication;
import com.telecomyt.jwportal.api.HttpApi;
import com.telecomyt.jwportal.constant.AppConfig;
import com.telecomyt.jwportal.http.base.BaseUrlInterceptor;
import com.telecomyt.jwportal.http.gson.CustomConverterFactory;
import com.telecomyt.jwportal.http.interceptor.CacheInterceptor;
import com.telecomyt.jwportal.http.interceptor.HttpLoggingInterceptor;
import com.telecomyt.jwportal.http.interceptor.SSLSocketClient;
import com.telecomyt.jwportal.http.progressmanager.ProgressManager;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;


public class RetrofitManager {
    public RetrofitManager() {
        initRetrofit();
    }

    private Retrofit mRetrofit;

    private static class NetWorkManagerHolder {
        private static final RetrofitManager INSTANCE = new RetrofitManager();
    }

    /**
     * 静态内部类单例
     */
    public static RetrofitManager getInstance() {
        return NetWorkManagerHolder.INSTANCE;
    }

    private void initRetrofit() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (AppConfig.OPEN_DEBUG) {
            //声明日志类
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor("OKHTTP");
            //设定日志级别
            httpLoggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
            httpLoggingInterceptor.setColorLevel(Level.INFO);
            builder.addInterceptor(httpLoggingInterceptor);

        }
        //设置公共参数
//        builder.addInterceptor(new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request oriainalReQuest = chain.request();
//                Request request;
//                HttpUrl build = oriainalReQuest.url().newBuilder()
//                        .addQueryParameter("", "")
//                        .build();
//                request = oriainalReQuest.newBuilder().url(build).build();
//                return chain.proceed(request);
//            }
//        });
        //设置header
//        builder.addInterceptor(new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request request = chain.request();
//                String token = "12B7007F297324662DDAE9A6EF5D7597";//模拟
//                Request.Builder requestBuilder = request.newBuilder()
//                        .addHeader("Content-Type", "application/json;charset=UTF-8");
//                requestBuilder.addHeader("token", TextUtils.isEmpty(token) ? "" : token);
//                Request request1 = requestBuilder.build();
//                return chain.proceed(request1);
//            }
//        });
        File cacheFile = new File(BaseApplication.getApplication().getCacheDir(), "HttpCache");//设置缓存路径
        int cacheSize = 10 * 1024 * 1024; // 10 MiB 设置缓存大小
        Cache cache = null;
        try {
            cache = new Cache(cacheFile, cacheSize);
        } catch (Exception e) {
            Log.e("OKHttp", "Could not create http cache", e);
        }


        builder.connectTimeout(AppConfig.NET_TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(AppConfig.NET_READ_TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(AppConfig.NET_WRITE_TIMEOUT, TimeUnit.SECONDS);

        builder.retryOnConnectionFailure(true);
        builder.addInterceptor(new CacheInterceptor());

        builder.addNetworkInterceptor(provideCacheInterceptor());
        //切换baseUrl
        builder.addInterceptor(new BaseUrlInterceptor());
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());//配置
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());

//         构建 OkHttpClient 时,将 OkHttpClient.Builder() 传入 with() 方法,进行初始化配置
        OkHttpClient client = ProgressManager.getInstance().with(builder).cache(cache).build();
        mRetrofit = new Retrofit.Builder()
                .addConverterFactory(CustomConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .baseUrl(AppConfig.BASR_URL_NOMAL)
                .build();
    }

    public <T> T createReq(Class<T> reqServer) {
        return mRetrofit.create(reqServer);
    }

    public HttpApi getDefaultReq() {
        return createReq(HttpApi.class);
    }


    public static Interceptor provideCacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());

                // re-write response header to force use of cache
                // 正常访问同一请求接口（多次访问同一接口），给30秒缓存，超过时间重新发送请求，否则取缓存数据
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(30, TimeUnit.SECONDS)
                        .build();

                return response.newBuilder()
                        .header("CACHE_CONTROL", cacheControl.toString())
                        .build();
            }
        };
    }
}
